#!/usr/bin/perl
#mdm_alert.cgi

require "./mdmjobs-lib.pl";
&ReadParse(); 

&header($text{'res_alert_detail'}, "", "index", 0, 1);
foreign_require("upgrade","upgrade-lib.pl");

&remote_error_setup(\&inst_error);
$| = 1;

#print $in{'listinput'};
local @in_members=split(/,/,$in{'listinput'});
local $grpinfo=&foreign_call("mdmgroups","get_groupinfo");
local %grpinfo=%$grpinfo;
local @group = split (/,/,$grpinfo{'[group]'});
local $own_upgrade;

local @devices;
foreach(@in_members){
	if (/^@/){
		local $grpname=$_;
		$grpname=~ s/@//;
		local $devs=$grpinfo{"$grpname"};
		local @devs=split(/,/,$devs);
		foreach $s (@devs){
			if ($s=~/\[This server\]/){
				$own_upgrade=1;
				next;
			}						
			push (@devices,$s);
		}
	}elsif(/^\[/){
		push (@devices,$_);
	}	
}

local %single;
local @servers;
foreach $serv (@devices){
	if (!$single->{"$serv"}++){
		push @servers,$serv;
	}
}

&rm_alertfile;
@devices = sort { $a cmp $b } @servers;
$p=0;
foreach $s (@devices){
	local ($rh = "READ$p", $wh = "WRITE$p");
	pipe($rh, $wh);
	select($wh); $| = 1; select(STDOUT);
	
	local $hostid = $s;
	$hostid =~ s/\[//;
	$hostid =~ s/\].*//;
	if (!fork()) {
		close($rh);
		local $rst;
		local @rst;
		local $localfile0=$config{'alertdir'}.$hostid.".mesg0";
		local $localfile1=$config{'alertdir'}.$hostid.".mesg1";
		local $rst1 = &remote_read($hostid,$localfile0,$config{'system_log'});
		push(@rst,$rst1);
		local $rst2 = &remote_read($hostid,$localfile1,$config{'webmin_log'});
		push(@rst,$rst2);
		print $wh &serialise_variable(\@rst);
		close($wh);
		exit;
	}

	close ($wh);
	$p++;	
}	

local @data;
local $logoper = "Get alert logs";
$p = 0;
foreach $s (@devices) {
	if (/\[This server\]/){
		next;
	}
	local $rh = "READ$p";
	local $line = <$rh>;
	close($rh);
	
	local $rv = &unserialise_variable($line);
	@rv=@$rv;
	if (! @rv){
		push @data,"$s return is: $text{'noanswer'}";
		print "<p>$s return is: $text{'noanswer'}";
	}else{
		local $line=join("; ",@rv);
		push @data,"$s return is: $line";
		print "<p>$s return is: $line\n";
	}
	
	$p++;	
}

&foreign_call("mdmhistory","mdm_log",$logoper,\@data);	

&remote_finished();	
&footer("./index.cgi", $text{'index_title'});		